package jp.dodododo.reloadable.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

import jp.dodododo.reloadable.io.ObjectInputStreamEx;

public abstract class SerializationUtils {
	public static byte[] serialize(Serializable obj) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
		serialize(obj, baos);
		return baos.toByteArray();
	}

	public static void serialize(Serializable obj, OutputStream outputStream) {
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(outputStream);
			out.writeObject(obj);
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		} finally {
			close(out);
		}
	}

	private static void close(OutputStream out) {
		try {
			if (out != null) {
				out.close();
			}
		} catch (IOException ignore) {
		}
	}

	public static Object deserialize(byte[] objectData, ClassLoader loader) {
		ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
		return deserialize(bais, loader);
	}

	public static Object deserialize(InputStream inputStream, ClassLoader loader) {
		ObjectInputStream in = null;
		try {
			in = new ObjectInputStreamEx(inputStream, loader);
			Object obj = in.readObject();
			return obj;
		} catch (ClassNotFoundException ex) {
			throw new RuntimeException(ex);
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		} finally {
			close(in);
		}
	}

	private static void close(InputStream in) {
		try {
			if (in != null) {
				in.close();
			}
		} catch (IOException ignore) {
		}
	}
}
